<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车次编号" prop="trainCode">
        <el-select v-model="queryParams.trainCode" filterable remote clearable placeholder="请输入车次编号"
                   :remote-method="remoteMethodTrain" :loading="loading" size="small" style="width: 200px" allow-create>
          <el-option v-for="item in trainOptions" :key="item.code" :label="item.code" :value="item.code"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['base:train-carriage:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['base:train-carriage:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDelete" v-hasPermi="['base:train-carriage:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['base:train-carriage:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload" size="mini" @click="handleImport"
                   v-hasPermi="['base:train-carriage:add']">导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleClear"
                   v-hasPermi="['base:train-carriage:remove']">清空数据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="showImportError" type="danger" plain icon="el-icon-warning" size="mini"
                   @click="handleExportErrorData">导出错误详情
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="showImportError" type="warning" plain icon="el-icon-document-copy" size="mini"
                   @click="handleCopyErrorData">复制到剪贴板
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 折叠面板列表 -->
    <el-collapse v-model="activeNames">
      <el-collapse-item v-for="(group, index) in groupedTrainCarriages" :key="index" :name="index">
        <template slot="title">
          <div class="collapse-header">
            <span class="train-code">{{ group.trainCode }}</span>
            <span class="carriage-info">
							<span class="carriage-count">共 {{ group.carriages.length }} 节车厢</span>
							<span class="seat-info">总座位数: {{ group.totalSeats }} 座</span>
						</span>
            <span class="carriage-types">
							<el-tag v-for="(count, type) in group.seatTypeCounts" :key="type"
                      :type="getSeatTypeTagType(type)" size="small" style="margin-right: 5px;">
								{{ getSeatTypeLabel(type) }}: {{ count }}节
							</el-tag>
						</span>
          </div>
        </template>

        <!-- 折叠面板内容 -->
        <el-table :data="group.carriages" :row-style="{ height: '60px' }"
                  @selection-change="handleSelectionChange" v-loading="loading">
          <el-table-column show-overflow-tooltip type="selection" width="55" align="center"/>
          <el-table-column show-overflow-tooltip label="序号" type="index" align="center" prop="id"/>
          <el-table-column show-overflow-tooltip label="车次编号" align="center" prop="trainCode"/>
          <el-table-column show-overflow-tooltip label="厢号" align="center" prop="index"/>
          <el-table-column show-overflow-tooltip label="座位类型" align="center" prop="seatType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.seat_type" :value="scope.row.seatType"/>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="座位数" align="center" prop="seatCount"/>
          <el-table-column show-overflow-tooltip label="排数" align="center" prop="rowCount"/>
          <el-table-column show-overflow-tooltip label="列数" align="center" prop="colCount"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['base:train-carriage:edit']">修改
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['base:train-carriage:remove']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <pagination v-show="trainTotal>0" :total="trainTotal" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>

    <!-- 添加或修改火车车厢对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车次编号" prop="trainCode">
          <el-select v-model="form.trainCode" filterable placeholder="请选择车次" style="width: 100%">
            <el-option v-for="item in trainOptions" :key="item.code" :label="item.code" :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="厢号" prop="index">
          <el-input v-model="form.index" placeholder="请输入厢号"/>
        </el-form-item>
        <el-form-item label="座位类型" prop="seatType">
          <el-select v-model="form.seatType" placeholder="请选择座位类型">
            <el-option v-for="dict in getFilteredSeatTypes()" :key="dict.value" :label="dict.label"
                       :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排数" prop="rowCount">
          <el-input v-model="form.rowCount" placeholder="请输入排数"/>

        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">

        <el-button type="primary" @click="submitForm">确 定</el-button>

        <el-button @click="cancel">取 消</el-button>

      </div>

    </el-dialog>


    <!-- 导入对话框 -->

    <el-dialog :title="title" :visible.sync="importOpen" width="400px" append-to-body>

      <div class="import-tip" style="margin-bottom: 15px;">

        <p style="margin: 0 0 10px 0;">请按以下格式准备Excel文件：</p>

        <el-card class="box-card" shadow="never">

          <div class="text item">

            <p style="margin: 5px 0;">1. 车次编号（必填）：如 G1234</p>

            <p style="margin: 5px 0;">2. 厢号（必填）：如 1、2、3</p>

            <p style="margin: 5px 0;">3. 座位类型（必填）：1-一等座，2-二等座，3-商务座</p>

            <p style="margin: 5px 0;">4. 排数（必填）：如 20</p>

            <p style="margin: 5px 0; color: #E6A23C;">注意事项：</p>

            <p style="margin: 5px 0; color: #F56C6C;">- 同一车次内厢号不能重复</p>

            <p style="margin: 5px 0; color: #F56C6C;">- 车次必须是系统中已存在的车次</p>

            <p style="margin: 5px 0; color: #F56C6C;">- 座位类型对应固定列数：一等座4列、二等座5列、商务座2列</p>

          </div>

        </el-card>

        <div style="margin-top: 10px; display: flex; gap: 10px;">

          <el-link type="primary" @click="showExampleImage">

            查看Excel模板示例

          </el-link>

          <el-link type="primary" @click="handleDownloadTemplate">

            下载Excel模板

          </el-link>

        </div>

      </div>

      <el-upload ref="upload" class="upload-demo" :action="uploadExcelUrl" :headers="headers"
                 :on-success="handleExcelSuccess" :on-error="handleExcelError" :auto-upload="false"
                 :before-upload="beforeUpload" :limit="1" :on-exceed="handleExceed" :on-change="handleFileChange"
                 accept=".xlsx, .xls">

        <el-button slot="trigger" size="small" type="primary">上传文件</el-button>

        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload"
                   :disabled="!fileSelected">上传
        </el-button>

        <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件，且不超过5MB</div>

      </el-upload>

    </el-dialog>


    <!-- 添加示例图片对话框 -->

    <el-dialog title="Excel模板示例" :visible.sync="exampleImageVisible" width="500px" append-to-body>

      <div class="excel-example">

        <el-table :data="exampleData" border style="width: 100%">

          <el-table-column prop="trainCode" label="车次编号" width="120"/>

          <el-table-column prop="index" label="厢号" width="119"/>

          <el-table-column prop="seatType" label="座位类型" width="120"/>

          <el-table-column prop="rowCount" label="排数" width="100"/>

        </el-table>

      </div>

    </el-dialog>


    <!-- 清空对话框 -->

    <el-dialog :title="title" :visible.sync="clearOpen" width="500px" append-to-body>

      <el-form ref="clearForm" :model="clearForm" :rules="clearRules" label-width="80px">

        <el-form-item label="密码" prop="password">

          <el-input v-model="clearForm.password" type="password" placeholder="请输入登录密码" show-password/>

          <div style="color: #F56C6C; font-size: 12px; margin-top: 8px;">
            提示：清空操作将删除所有列车车厢数据且不可恢复，请谨慎操作！
          </div>

        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer">

        <el-button type="primary" @click="submitClearForm">确 定</el-button>

        <el-button @click="cancelClear">取 消</el-button>

      </div>

    </el-dialog>

  </div>

</template>


<script>
import {
  listTrainCarriage,
  getTrainCarriage,
  delTrainCarriage,
  addTrainCarriage,
  updateTrainCarriage,
  clearTrainCarriage
} from "@/api/base/train-carriage";

import {
  listTrain
} from "@/api/base/train";


export default {

  name: "Train-carriage",

  dicts: ['seat_type'].filter(type => type !== '4'),

  data() {

    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组
      indexs: [],
      // 非单个禁用
      single: true,

      // 非多个禁用

      multiple: true,

      // 显示搜索条件

      showSearch: true,

      // 总条数

      total: 0,

      // 列车总数（用于分页）

      trainTotal: 0,

      // 添加车次选项数据

      trainOptions: [],

      // 火车车厢表格数据

      trainCarriageList: [],

      // 分组后的火车车厢数据

      groupedTrainCarriages: [],

      // 折叠面板激活项

      activeNames: [],

      // 示例图片

      exampleImageVisible: false,

      exampleData: [{

        trainCode: 'G1234',

        index: '1',

        seatType: '1',

        rowCount: '20'

      }, {

        trainCode: 'G1234',

        index: '2',

        seatType: '2',

        rowCount: '25'

      }, {

        trainCode: 'G1234',

        index: '3',

        seatType: '3',

        rowCount: '30'

      }],

      // 弹出层标题

      title: "",

      // 是否显示弹出层

      open: false,

      // 导入对话框

      importOpen: false,

      //上传地址

      uploadExcelUrl: process.env.VUE_APP_BASE_API + "/base/train-carriage/importExcel",

      //请求头

      headers: {
        'Authorization': 'Bearer ' + this.$store.getters.token
      },

      //禁止上传按钮

      fileSelected: false,

      // 查询参数

      queryParams: {

        pageNum: 1,

        pageSize: 10,

        trainCode: null,

      },

      // 表单参数

      form: {},

      // 表单校验

      rules: {

        trainCode: [

          {
            required: true,
            message: "车次编号不能为空",
            trigger: "change"
          }

        ],

        index: [

          {
            required: true,
            message: "厢号不能为空",
            trigger: "blur"
          }

        ],

        seatType: [

          {
            required: true,
            message: "座位类型|枚举[SeatTypeEnum]不能为空",
            trigger: "change"
          }

        ],

        rowCount: [

          {
            required: true,
            message: "排数不能为空",
            trigger: "blur"
          }

        ],

      },

      // 导入错误数据

      errorData: [],

      // 是否显示导入错误按钮

      showImportError: false,

      // 清空对话框

      clearOpen: false,

      // 清空表单

      clearForm: {

        password: undefined

      },

      // 清空表单校验

      clearRules: {

        password: [

          {
            required: true,
            message: "请输入登录密码",
            trigger: "blur"
          }

        ]

      }

    };

  },

  created() {

    this.getList();

    this.getTrainList();

  },

  methods: {

    // 获取车次列表

    getTrainList() {

      listTrain().then(response => {

        this.trainOptions = response.rows;

      });

    },


    // 远程搜索车次方法

    remoteMethodTrain(query) {

      if (query) {

        this.loading = true;

        listTrain({
          code: query
        }).then(response => {

          this.trainOptions = response.rows;

          this.loading = false;

        });

      } else {

        this.trainOptions = [];

      }

    },


    /** 查询火车车厢列表 */

    getList() {

      this.loading = true;

      listTrainCarriage(this.queryParams).then(response => {

        // 获取所有车厢数据

        this.trainCarriageList = response.rows;


        // 记录原始总数(车厢数量)

        this.total = response.total;


        // 分组处理数据

        this.groupCarriages();


        // 进行分页处理

        this.handleTrainPagination();


        this.loading = false;

      });

    },


    // 分组处理车厢数据

    groupCarriages() {
      // 创建一个Map以按trainCode分组
      const groups = {};
      this.trainCarriageList.forEach(item => {
        if (!groups[item.trainCode]) {
          groups[item.trainCode] = [];
        }
        groups[item.trainCode].push(item);
      });


      this.groupedTrainCarriages = Object.keys(groups).map(trainCode => {

        // 按厢号排序
        const carriages = groups[trainCode].sort((a, b) => a.index - b.index);
        // 计算总座位数
        const totalSeats = carriages.reduce((sum, carriage) => {
          return sum + (parseInt(carriage.seatCount) || 0);
        }, 0);


        // 统计各类型座位的车厢数

        const seatTypeCounts = {};

        carriages.forEach(carriage => {

          if (!seatTypeCounts[carriage.seatType]) {

            seatTypeCounts[carriage.seatType] = 0;

          }

          seatTypeCounts[carriage.seatType]++;

        });


        return {

          trainCode,

          carriages,

          totalSeats,

          seatTypeCounts

        };

      });

    },


    // 处理列车级别的分页

    handleTrainPagination() {

      // 获取所有分组后的列车

      const allTrains = [...this.groupedTrainCarriages];


      // 记录列车总数

      this.trainTotal = allTrains.length;


      // 如果需要手动进行分页处理，可以在这里实现

      // const pageSize = this.queryParams.pageSize;

      // const pageNum = this.queryParams.pageNum;

      // const start = (pageNum - 1) * pageSize;

      // const end = start + pageSize;

      // this.groupedTrainCarriages = allTrains.slice(start, end);

    },


    /** 分页操作 */

    handleCurrentChange(val) {

      this.queryParams.pageNum = val;

      this.getList();

    },


    /** 每页条数变化 */

    handleSizeChange(val) {

      this.queryParams.pageSize = val;

      this.getList();

    },


    // 获取座位类型标签样式

    getSeatTypeTagType(type) {

      const typeMap = {

        '1': 'success', // 一等座

        '2': '', // 二等座

        '3': 'warning' // 商务座

      };

      return typeMap[type] || '';

    },


    // 获取座位类型标签文本

    getSeatTypeLabel(type) {
      const labels = this.dict.type.seat_type.filter(item => item.value !== '4'); // 过滤掉硬卧选项
      const found = labels.find(item => item.value === type);
      return found ? found.label : `类型${type}`;
    },

    // 在表单中显示座位类型选项时过滤
    getFilteredSeatTypes() {
      return this.dict.type.seat_type.filter(item => item.value !== '4');
    },

    // 取消按钮

    cancel() {

      this.open = false;

      this.reset();

    },

    // 表单重置

    reset() {

      this.form = {

        id: null,

        trainCode: null,

        index: null,

        seatType: null,

        seatCount: null,

        rowCount: null,

        colCount: null,

        createTime: null,

        updateTime: null

      };

      this.resetForm("form");

    },

    /** 搜索按钮操作 */

    handleQuery() {

      this.queryParams.pageNum = 1;

      this.getList();

    },

    /** 重置按钮操作 */

    resetQuery() {

      this.resetForm("queryForm");

      this.handleQuery();

    },

    // 多选框选中数据

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.indexs = selection.map(item => item.index)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */

    handleAdd() {

      this.reset();

      this.open = true;

      this.title = "添加列车车厢";

    },

    /** 修改按钮操作 */

    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTrainCarriage(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改列车车厢";

      });

    },

    /** 提交按钮 */

    submitForm() {

      this.$refs["form"].validate(valid => {

        if (valid) {

          if (this.form.id != null) {

            updateTrainCarriage(this.form).then(response => {

              this.$modal.msgSuccess("修改成功");

              this.open = false;

              this.getList();

            });

          } else {

            addTrainCarriage(this.form).then(response => {

              this.$modal.msgSuccess("新增成功");

              this.open = false;

              this.getList();

            });

          }

        }

      });

    },

    /** 下载模板操作 */

    handleDownloadTemplate() {

      this.download('base/train-carriage/downloadTemplate', {}, `列车车厢模板${new Date().getTime()}.xlsx`);

    },

    // 显示示例图片

    showExampleImage() {

      this.exampleImageVisible = true;

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const indexs = row.index || this.indexs;
      this.$modal.confirm('是否确认删除列车车厢为"' + indexs + '"的数据项？').then(function () {
        return delTrainCarriage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.importOpen = true;
      this.title = "数据导入";
      // 重置错误数据
      this.errorData = [];
    },
    submitUpload() {
      this.$refs.upload.submit();
    },

    // 上传成功回调

    handleExcelSuccess(res, file) {

      if (res.code === 200) {

        // 检查是否有错误数据
        if (res.data && res.data.errorList && res.data.errorList.length > 0) {
          this.errorData = res.data.errorList;
          this.showImportError = true; // 显示错误按钮
          this.$modal.msgError(
            `导入完成：成功 ${res.data.successCount || 0} 条，失败 ${res.data.errorList.length} 条`);
        } else {
          this.$modal.msgSuccess("导入成功");
          this.showImportError = false; // 隐藏错误按钮
          this.errorData = [];
        }

        this.importOpen = false;
        this.getList();
      } else {
        this.$modal.msgError(res.msg || "导入失败");
      }
      this.$refs.upload.clearFiles(); // 清空已上传的文件列表
    },

    // 上传失败回调

    handleExcelError(err, file) {

      this.$modal.msgError("上传Excel失败，请重试");

      this.$refs.upload.clearFiles(); // 清空已上传的文件列表

    },

    // 上传前的文件校验

    beforeUpload(file) {

      const isExcel = file.type === 'application/vnd.ms-excel' || file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

      const isLt5M = file.size / 1024 / 1024 < 5;


      if (!isExcel) {

        this.$message.error('只能上传Excel文件!');

      }

      if (!isLt5M) {

        this.$message.error('上传文件大小不能超过5MB!');

      }

      return isExcel && isLt5M;

    },

    // 文件超出数量限制时的处理

    handleExceed(files, fileList) {

      this.$message.warning('只能上传一个文件');

    },

    handleFileChange(file, fileList) {
      this.fileSelected = fileList.length > 0;
    },

    /** 导出按钮操作 */
    handleExport() {
      const exportParams = { ...this.queryParams };
      // 删除分页相关参数
      delete exportParams.pageNum;
      delete exportParams.pageSize;
      this.download('base/train-carriage/export', {exportParams}, `列车车厢_${new Date().getTime()}.xlsx`)
    },

    // 导出错误数据
    handleExportErrorData() {
      this.$modal.loading("正在导出数据，请稍候...");

      // 使用后端接口导出Excel
      const formData = new FormData();
      formData.append("errorData", JSON.stringify(this.errorData));

      // 发送POST请求
      fetch(process.env.VUE_APP_BASE_API + "/base/train-carriage/exportErrorData", {
        method: "POST",
        body: formData,
        headers: {
          // 添加认证token
          "Authorization": "Bearer " + this.$store.getters.token
        }
      })
        .then(response => {
          if (response.ok) {
            return response.blob();
          }
          throw new Error("导出失败");
        })
        .then(blob => {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = url;
          a.download = "列车车厢导入错误数据_" + new Date().getTime() + ".xlsx";
          document.body.appendChild(a);
          a.click();
          window.URL.revokeObjectURL(url);
          this.$modal.closeLoading();
        })
        .catch(error => {
          console.error("导出错误:", error);
          this.$modal.closeLoading();
          this.$modal.msgError("导出失败");
        });
    },

    // 复制错误数据到剪贴板
    handleCopyErrorData() {
      if (!this.errorData || this.errorData.length === 0) {
        this.$message.error('没有错误数据可复制');
        return;
      }

      // 获取座位类型标签文本
      const getSeatTypeLabel = (type) => {
        switch (type) {
          case "1":
            return "一等座";
          case "2":
            return "二等座";
          case "3":
            return "商务座";
          default:
            return `未知类型(${type})`;
        }
      };

      // 创建表头
      const header = ['ID', '车次编号', '厢号', '座位类型', '排数', '列数', '座位数', '错误原因'].join('\t');

      // 创建数据行
      const rows = this.errorData.map(item => {
        const colCount = this.getSeatTypeColumns(item.seatType);
        const seatCount = this.calculateSeatCount(item.rowCount, item.seatType);
        const seatTypeText = getSeatTypeLabel(item.seatType);

        return [
          item.id || '-',
          item.trainCode || '-',
          item.index || '0',
          `${seatTypeText}(${item.seatType})`,
          item.rowCount || '0',
          colCount,
          seatCount,
          item.errorMsg || '数据验证失败'
        ].join('\t');
      });

      // 组合表头和数据行
      const textData = [header, ...rows].join('\n');

      // 使用剪贴板API复制文本
      const textarea = document.createElement('textarea');
      textarea.value = textData;
      document.body.appendChild(textarea);
      textarea.select();

      try {
        document.execCommand('copy');
        this.$message({
          message: `成功复制${this.errorData.length}条错误数据到剪贴板`,
          type: 'success',
          duration: 3000
        });
      } catch (err) {
        this.$message.error('复制失败，请手动复制');
        console.error('复制失败:', err);
      } finally {
        document.body.removeChild(textarea);
      }
    },

    // 重新导入

    handleRetryImport() {
      this.handleImport(); // 打开导入对话框
    },

    // 根据座位类型获取列数
    getSeatTypeColumns(seatType) {
      switch (seatType) {
        case "1":
          return 4; // 一等座
        case "2":
          return 5; // 二等座
        case "3":
          return 2; // 商务座
        default:
          return 4;
      }
    },

    // 计算座位数
    calculateSeatCount(rowCount, seatType) {
      if (!rowCount) rowCount = 0;
      return rowCount * this.getSeatTypeColumns(seatType);
    },

    /** 清空按钮操作 */
    handleClear() {
      this.clearOpen = true;
      this.title = "清空列车车厢数据";
    },
    /** 提交清空表单 */
    submitClearForm() {
      this.$refs["clearForm"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认清空所有列车车厢数据？').then(() => {
            return clearTrainCarriage({
              password: this.clearForm.password
            });
          }).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("清空成功");
              this.clearOpen = false;
              this.resetClearForm();
              this.getList();
            } else {
              this.$modal.msgError(response.msg || "清空失败");
            }
          }).catch(error => {
            console.error("清空失败:", error);
            this.$modal.msgError("清空失败：" + (error.msg || "未知错误"));
          });
        }
      });
    },
    /** 取消清空 */
    cancelClear() {
      this.clearOpen = false;
      this.resetClearForm();
    },
    /** 重置清空表单 */
    resetClearForm() {
      this.clearForm = {
        password: undefined
      };
      this.resetForm("clearForm");
    },

  }

};
</script>


<style scoped>
.collapse-header {

  display: flex;

  align-items: center;

  font-size: 14px;

}

.train-code {

  font-weight: bold;

  margin-right: 20px;

  min-width: 80px;

}

.carriage-info {

  display: flex;

  align-items: center;

  margin-right: 20px;

}

.carriage-count {

  font-weight: bold;

  margin-right: 15px;

}

.seat-info {

  color: #606266;

}

.carriage-types {

  margin-left: auto;

}


/* 替代方案 - 使用 ::v-deep 选择器 */

::v-deep .el-collapse-item__wrap {

  padding: 0 0 0 20px;

}


::v-deep .el-collapse-item__content {

  padding-bottom: 15px;

}


::v-deep .el-collapse-item {

  margin-bottom: 5px;

}

/* 导入错误对话框相关样式 */
.import-error-dialog ::v-deep .el-dialog__body {
  padding: 20px;
}

.error-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.error-summary {
  display: flex;
  align-items: center;
  font-size: 15px;
}

.error-actions {
  display: flex;
  gap: 10px;
}

/* 表格行样式 */
::v-deep .el-table .warning-row {
  background: #fdf5e6;
}

::v-deep .el-table .error-row {
  background: #fef0f0;
}
</style>
